<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/13
 * Time: 11:50
 */

namespace app\common\cachemodel;

use app\common\model\BaseCache;
use XznsTools\cache\CacheManage;

/**
 * 校准生辰事件模型
 * Class RectificationEvent
 * @package app\common\cachemodel
 */
class RectificationEvent extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_rectification_event';

    protected $cacheModel = 'rectification.rectification_event';

    public function rectification()
    {
        return $this->belongsTo('rectification');
    }

    /**
     * 保存事件信息
     * @param $event_data
     * @return bool
     */
    public function SaveData($event_data)
    {
        try
        {
            $this->saveAll($event_data);
        }
        catch (\Exception $e)
        {
            return false;
        }
        return true;
    }

    /**
     * 更细事件信息
     * @param $reid
     * @param $event_data
     * @return bool
     */
    public function UpdateData($reid, $event_data)
    {
        try
        {
            // 删除校准生辰事件表
            $this->where(['reid' => $reid])->delete();
            $event_datas = [];
            foreach ($event_data as $k => $ev)
            {
                if (isset($ev['id']))
                {
                    unset($ev['id']);
                }
                $event_datas[] = $ev;
            }
            // 存入校准生辰事件表
            $this->saveAll($event_datas);
        }
        catch (\Exception $e)
        {
            return false;
        }
        return true;
    }


    /**
     * 批量获取事件详情
     * @param $ids
     * @param $field
     * @return array|false
     * @throws \Exception
     */
    public function getEventDetail($ids, $field = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->batchGetCache($ids, function ($ids)
            {
                return $this->where(['id' => ['in', $ids]])->column('reid,time,type,desc', 'id');
            }, $field, 'event_details');

        return $data;
    }

    /**
     * 删除事件详情缓存
     * @param $id
     * @param $reid
     * @throws \Exception
     */
    public function rmEventDetailCache($id, $reid)
    {
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache('event_details');
        CacheManage::getInstance()->setCacheConfig('rectification.rectification_event', $reid)->rmCache();
    }

    /**
     * 数据库批量获取校准生辰事件数据
     * @param int $cid
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $field = 'id,status,reid,time,type,desc';
        try
        {
            $data = $this->where('reid', 'in', $ids)
                ->field($field)
                ->selectOrFail();
            $data = json_decode(json_encode($data, true), true);
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }
}
